<template>
  <Container class="structure-tree-group-item" tabindex="1" @blur.native.prevent="itemBlurHandler">

    <div class="group-item"
         :class="{'active': groupItem._highlight}"
         @click.stop="locationTargetGroupItem(groupItem)"
         @mouseenter="itemMouseenterHandle"
         @mouseleave="itemMouseleaveHandle">
      <div class="header"
           v-contextmenu:groupItemContextmenu>
        <a href="javascript:;" class="toggle-btn color-white" @click="layoutItemTreeVisible = !layoutItemTreeVisible">
          <Icon :type="layoutItemTreeVisible ? 'ios-arrow-down':'ios-arrow-up'"  size="14"/>
        </a>
        <Icon type="md-folder" size="18" style="margin-top: -2px; margin-left: 3px; margin-right: 3px;"/>
        <span :title="groupItem.groupItemName" style="cursor: pointer;"
              @dblclick="nameDblclickHandler">{{groupItem.groupItemName ? $PnUtil.cutString(groupItem.groupItemName, 9) : '组'}}</span>

        <div class="toolbar">
          <a class="m-l-5px" href="javascript:;" v-if="alongShowTargetIdList.indexOf(groupItem.groupItemId) > -1"
             @click="$DesignerCommonUtil.toggleAlongShowLayout('groupItems', [groupItem.groupItemId], 'cancel')">
            <Icon custom="iconfont icon-along-show"/>
          </a>
          <a class="m-l-5px" href="javascript:;" v-if="groupItem.display == 'none'"
             @click="$DesignerCommonUtil.groupItemShow([groupItem.groupItemId])">
            <Icon type="md-eye-off" size="14"/>
          </a>
          <a class="m-l-5px" href="javascript:;" v-if="!groupItem.draggable"
             @click="$DesignerCommonUtil.groupItemUnLock([groupItem.groupItemId])">
            <Icon custom="iconfont iconlock"/>
          </a>
        </div>

        <div class="clearfix"></div>
      </div>
      <div class="content clearfix" :class="{'content-active': layoutItemTreeVisible}">

        <StructureTreeLayoutItem v-show="layoutItemTreeVisible" v-for="(layoutItem, index) in layoutItemTreeData"
                                 :key="index"
                                 :belong-group-item="true"
                                 :layoutItem="layoutItem" @itemClick="layoutItemClickHandler"></StructureTreeLayoutItem>

      </div>
    </div>

    <div v-if="renameEdit" class="rename-input" @click.stop>
      <input v-focus v-model="formData.groupItemName"
             @focus="renameInputFocusHandler"
             @blur="renameInputBlurHandler"
             @keyup.enter="renameInputBlurHandler"/>
    </div>

    <v-contextmenu ref="groupItemContextmenu">
      <v-contextmenu-item @click="groupItemContextMenuClick('menu_setTop')"><Icon custom="iconfont iconvertical-align-top" /> 置顶</v-contextmenu-item>
      <v-contextmenu-item @click="groupItemContextMenuClick('menu_setDown')"><Icon custom="iconfont iconvertical-align-botto" /> 置底</v-contextmenu-item>

      <v-contextmenu-item v-if="groupItem.display == 'block'" @click="groupItemContextMenuClick('menu_hide')"><Icon type="md-eye-off" size="14"/> 隐藏</v-contextmenu-item>
      <v-contextmenu-item v-else @click="groupItemContextMenuClick('menu_show')"><Icon type="md-eye" size="14"/> 显示</v-contextmenu-item>
      <v-contextmenu-item @click="groupItemContextMenuClick('menu_reverseHide')"><Icon custom="iconfont icon-reverse-hide" size="15"/> 反选隐藏</v-contextmenu-item>
      <v-contextmenu-item @click="groupItemContextMenuClick('menu_reverseShow')"><Icon custom="iconfont icon-reverse-show" size="15"/> 反选显示</v-contextmenu-item>
      <v-contextmenu-item v-if="groupItem.draggable" @click="groupItemContextMenuClick('menu_lock')"><Icon custom="iconfont iconlock" /> 锁定</v-contextmenu-item>
      <v-contextmenu-item v-else @click="groupItemContextMenuClick('menu_unlock')"><Icon custom="iconfont iconunlock" /> 解锁</v-contextmenu-item>
      <v-contextmenu-item v-if="alongShowTargetIdList.indexOf(groupItem.groupItemId) < 0" @click="groupItemContextMenuClick('menu_alongShowEnter')"><Icon custom="iconfont icon-along-show" /> 单独显示图层</v-contextmenu-item>
      <v-contextmenu-item v-else @click="groupItemContextMenuClick('menu_alongShowCancel')"><Icon type="md-close-circle" size="14"/> 取消独立显示</v-contextmenu-item>
      <v-contextmenu-item divider></v-contextmenu-item>
      <v-contextmenu-item @click="groupItemContextMenuClick('menu_rename')"><Icon type="md-create" size="15"/> 重命名</v-contextmenu-item>
      <v-contextmenu-item @click="groupItemContextMenuClick('menu_undoGroupItem')"><Icon custom="iconfont icon-undo-group-item" size="13" /> 取消组合</v-contextmenu-item>
      <v-contextmenu-item divider></v-contextmenu-item>
      <v-contextmenu-item @click="groupItemContextMenuClick('menu_copyGroupItem')"><Icon type="md-copy" size="15"/> 复制</v-contextmenu-item>
      <v-contextmenu-item divider></v-contextmenu-item>
      <v-contextmenu-item @click="groupItemContextMenuClick('menu_deleteGroupItem')"><Icon type="md-trash" size="15"/> 删除组</v-contextmenu-item>
    </v-contextmenu>

  </Container>
</template>

<script>

  import Vue from 'vue'

  // 右键菜单组件
  import contentmenu from 'v-contextmenu'
  import '../../../../assets/css/contextmenu.css'
  Vue.use(contentmenu);

  import _ from "lodash";

  import StructureTreeLayoutItem from './StructureTreeLayoutItem'

  import { createHelpers } from 'vuex-map-fields';

  const { mapFields } = createHelpers({
    getterType: 'designer/getField',
    mutationType: 'designer/updateField',
  });

  export default {
    name: 'StructureTreeGroupItem',
    components: {
      StructureTreeLayoutItem
    },
    props: {
      groupItem: {
        type: Object,
        require: true
      }
    },
    data() {
      return {
        renameEdit: false,
        formData: {
          groupItemName: ''
        },
        layoutItemTreeVisible: false
      }
    },
    mounted() {

    },
    methods: {

      locationTargetGroupItem () {
        this.$refs.groupItemContextmenu.hide();
        this.$store.commit('designer/setCurrentSelectGroupItemId', this.groupItem.groupItemId);

        this.$store.commit('designer/setCurrentSelectLayoutItemId', '');
        this.$store.commit('designer/setCurrentSelectLayoutItemIds', []);
        this.$store.commit('designer/setRightSidebarFuncCompConfigFormName', '');

        this.$emit('itemClick', {layoutItemId: null, groupItemId: this.groupItem.groupItemId})
      },

      nameDblclickHandler () {
        this.renameEdit = true;
        if (this.groupItem.groupItemName) {
          this.formData.groupItemName = this.groupItem.groupItemName
        }else {
          this.formData.groupItemName = '组'
        }
      },

      renameInputFocusHandler () {
        setTimeout(() => {
          $(document).unbind('keydown');
          $(document).unbind('keyup');
        }, 100)
      },

      renameInputBlurHandler () {
        this.$store.commit('designer/setGroupItemName', {
          id: this.groupItem.groupItemId,
          name: this.formData.groupItemName
        });
        this.renameEdit = false;
        this.$EventBus.$emit('pn_closeStructureTreeRenameModal')
      },

      groupItemContextMenuClick (name) {
        if (!this.currentSelectGroupItemId && this.currentSelectGroupItemIds.length == 0) {
          this.$Message.error('并未选中任何组');
          return
        }

        let groupItemIds = _.compact(_.union([this.currentSelectGroupItemId], this.currentSelectGroupItemIds.concat()));

        switch (name) {
          case 'menu_setTop':
            this.$DesignerCommonUtil.groupItemSetTop(groupItemIds);
            break;
          case 'menu_setDown':
            this.$DesignerCommonUtil.groupItemSetDown(groupItemIds);
            break;
          case 'menu_hide':
            this.$DesignerCommonUtil.groupItemHide(groupItemIds);
            break;
          case 'menu_show':
            this.$DesignerCommonUtil.groupItemShow(groupItemIds);
            break;
          case 'menu_reverseHide':
            this.$DesignerCommonUtil.groupItemReverseHideOrShow(groupItemIds, true);
            break;
          case 'menu_reverseShow':
            this.$DesignerCommonUtil.groupItemReverseHideOrShow(groupItemIds, false);
            break;
          case 'menu_lock':
            this.$DesignerCommonUtil.groupItemLock(groupItemIds);
            break;
          case 'menu_unlock':
            this.$DesignerCommonUtil.groupItemUnLock(groupItemIds);
            break;
          case 'menu_alongShowEnter':
            this.$DesignerCommonUtil.toggleAlongShowLayout('groupItems', groupItemIds, 'enter')
            break;
          case 'menu_alongShowCancel':
            this.$DesignerCommonUtil.toggleAlongShowLayout('groupItems', groupItemIds, 'cancel')
            break;
          case 'menu_rename':
            this.nameDblclickHandler();
            break;
          case 'menu_undoGroupItem':
            this.$DesignerCommonUtil.groupItemUndo(groupItemIds);
            break;
          case 'menu_copyGroupItem':
            this.$DesignerCommonUtil.groupItemCopy(groupItemIds);
            break;
          case 'menu_deleteGroupItem':
            this.$DesignerCommonUtil.groupItemDelete(groupItemIds);
            break;
          default:
        }
      },

      itemMouseenterHandle () {
        this.$store.commit('designer/setCurrentHoverGroupItemId', this.groupItem.groupItemId)
      },

      itemMouseleaveHandle () {
        this.$store.commit('designer/setCurrentHoverGroupItemId', '')
      },

      layoutItemClickHandler (params) {
        this.$emit('itemClick', params)
      },

      itemBlurHandler () {
        if (this.$refs.groupItemContextmenu) {
          setTimeout(() => {
            this.$refs.groupItemContextmenu.hide()
          }, 300)
        }
      }

    },
    computed: {
      ...mapFields({
        pageMetadata: 'pageMetadata',
        currentSelectLayoutItemId: 'currentSelectLayoutItemId',
        currentSelectLayoutItemIds: 'currentSelectLayoutItemIds',
        currentSelectGroupItemId: 'currentSelectGroupItemId',
        currentSelectGroupItemIds: 'currentSelectGroupItemIds',
        alongShowTargetIdList: 'alongShowTargetIdList'
      }),

      layoutItemTreeData () {
        let treeData = [];

        let storeLayoutGroup = this.$PnUtil.deepClone(this.pageMetadata.layout.layoutGroup);

        if (this.layoutItemTreeVisible) {
          if (storeLayoutGroup.length > 0) {
            storeLayoutGroup.forEach(groupItem => {

              if (groupItem.id == this.groupItem.groupItemId) {
                groupItem.layoutItemIds.forEach(layoutItemId => {

                  let tmpLayoutItem = this.$PnUtil.deepClone(this.$store.getters['designer/getLayoutItemById'](layoutItemId));

                  let layoutItem = {
                    type: 'layoutItem',
                    layoutItemId: tmpLayoutItem.id,
                    layoutItemName: tmpLayoutItem.name,
                    layoutItemAliasName: tmpLayoutItem.aliasName,
                    layoutItemDisplay: tmpLayoutItem.layoutItemConfigData.display,
                    layoutItemDraggable: tmpLayoutItem.layoutItemConfigData.draggableEnabled,
                    componentId: tmpLayoutItem.component.id,
                    componentName: tmpLayoutItem.component.name,
                    zIndex: tmpLayoutItem.layoutItemConfigData.zIndex
                  };

                  if (this.currentSelectLayoutItemIds.length > 0) {
                    this.currentSelectLayoutItemIds.indexOf(tmpLayoutItem.id) > -1 ? layoutItem._highlight = true : layoutItem._highlight = false
                  }else {
                    this.currentSelectLayoutItemId == tmpLayoutItem.id ? layoutItem._highlight = true : layoutItem._highlight = false
                  }

                  treeData.push(layoutItem)
                });
              }

            });

            treeData.sort(function (a, b) {
              return b.zIndex > a.zIndex ? 1 : -1
            });
          }
        }

        return treeData
      }
    }
  }
</script>

<style lang="less" scoped>

  .highlight {
    background-color: #ff9900;
    padding-left: 5px;
    padding-right: 5px;
  }

  .structure-tree-group-item {
    position: relative;
    .rename-input {
      width: 150px;
      position: absolute;
      top: 8px;
      left: 48px;
      z-index: 999;
      input {
        width: 140px;
      }
    }
    &:focus {
      outline: 0;
    }
  }

  .group-item {
    width: 100%;
    height: auto;
    background-color: #424242;
    &:hover {
      .header {
        background-color: #757575;
      }
    }
    &.active {
      .header {
        background-color: #fb8c00;
      }
    }
    .header {
      background-color: #424242;
      line-height: 38px;
      font-size: 12px;
      padding: 0px 10px 0px 10px;
      color: #fff;
      .toggle-btn {
        i {
          margin-top: -2px;
        }
        &:hover {
          color: #fff;
          text-shadow: 0px 0px 5px #000
        }
      }
      .toolbar {
        float: right;
        a {
          color: #fff;
        }
      }
    }
    .content {
      position: relative;
    }

    .content-active {

    }

  }

  input {
    color: #212121;
  }

</style>
